package com.lagou.service;

import com.google.common.cache.*;
import com.lagou.SerializeUtil;
import com.lagou.entity.Position;
import com.lagou.repository.PositionRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;


import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException;

@Service
public class PositionInfoServiceImp implements PositionInfoService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private PositionRepository positionRepository;

    //CacheLoader的方式创建
    LoadingCache<String, Object> cache = CacheBuilder.newBuilder()
            //加附加功能
            //最大数 3
            .recordStats()
            .build(new CacheLoader<String, Object>() {
                //读取数据源
                @Override
                public Object load(String key) throws Exception {
                    //return Constants.hm.get(key);
                    //从redis中获取数据源
                    System.out.println("guava 回源redis!");
                    Object list = getPositionFromRedis(key);
                    return list;
                }
            });

    public Object getList(String guavaKey) {
        try {
            Object positionList = cache.get(guavaKey);
            System.out.println(cache.stats());
            return positionList;
        } catch (ExecutionException e) {
            e.printStackTrace();
            return null;
        }

    }

    public Object getPositionFromRedis(String redisKey){
        JedisPoolConfig Config = new JedisPoolConfig();
        Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
        jedisClusterNode.add(new HostAndPort("192.168.18.132",7001));
        jedisClusterNode.add(new HostAndPort("192.168.18.132",7002));
        jedisClusterNode.add(new HostAndPort("192.168.18.132",7003));
        jedisClusterNode.add(new HostAndPort("192.168.18.132",7004));
        jedisClusterNode.add(new HostAndPort("192.168.18.132",7005));
        jedisClusterNode.add(new HostAndPort("192.168.18.132",7006));
        jedisClusterNode.add(new HostAndPort("192.168.18.132",7007));
        jedisClusterNode.add(new HostAndPort("192.168.18.132",7008));
        JedisCluster jcd = new JedisCluster(jedisClusterNode, Config);

        byte[] list = jcd.get(redisKey.getBytes());
        if(list ==null){//redis缓存中为空
            //从数据库中获取
            System.out.println("redis 回源数据库！");
            List<Position> positions = positionRepository.queryPositionList();
            jcd.set(redisKey.getBytes(),SerializeUtil.serialize(positions));
            return positions;
        }

        return SerializeUtil.unserialize(list);
    }
}
